const User = require("../Models/user");

// 批量添加用户
exports.addUserPlus = function (data) {
    return new Promise(resolve => {
        User.collection.insertMany(data, {ordered: false},function (err, res) {
            resolve(err);
            console.log('保存成功：');
        });
    })
};

// 获取用户列表
exports.getUserList = async ctx => {
    let query = ctx.request.query;
    let page = Number(query.page);
    let limit = Number(query.limit);
    let selected = {};
    // 判断 query 参数是否> 2
    if (Object.keys(query).length > 2) {
        delete query.page;
        delete query.limit;
        selected = query;
    }
    // 查询总数
    const maxNum = await User.estimatedDocumentCount((err, num) => err ? console.log(err) : num);
    await User
        .find(selected)
        .skip(limit * (page-1))
        .limit(limit)
        .then(data => {
            ctx.body = {
                status: 0,
                count: maxNum,
                data
            }
        })
        .catch(err => console.log(err));
};

// 删除用户
exports.delete = async ctx => {
    const data = ctx.request.body.data;
    // 调整数据格式
    let selected = [];
    for (let item in data) {
        selected.push({_id: data[item]._id});
    }
    await User.remove({_id: { $in: selected }})
        .then(data => {
            //console.log(data);
            console.log('删除成功');
            ctx.body = {
                status: 200,
                data
            }
        }).catch(err => console.log(err));
};

// 用户数据更新
exports.update = async ctx => {
    const data = ctx.request.body;
    const _id = data._id;
    const name = data.name;
    await User
        .update({_id}, {$set: {name}})
        .then(data => {
            console.log(data);
            console.log('修改成功');
            ctx.body = {
                status: 200,
                data
            }
        })
};